import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { hashHistory } from 'react-router'

import * as userInfoActionsFromOtherFile from '../../actions/userinfo' 

import Header from '../../components/Header';
import LoginComponent from '../../components/Login/index.jsx';
class Login extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            checking: true
        }
        this.loginHandle = this.loginHandle.bind(this)
    }
    render() {
        return (
            <div>
                <Header
                    {...{
                        title:'登录页面'
                    }}
                />
                {   // 等待验证之后，再显示登录信息
                    this.state.checking 
                    ?  <div>正在验证是否已登录</div> 
                    :<LoginComponent 
                        {...{
                           loginHandle:this.loginHandle 
                        }}
                    />
                }
            </div>
        )
    }
    componentDidMount() {
        //验证是否登录了
        this.doCheck()
    }
    //验证是否登录了
    doCheck(){
        //从redux中拿到userInfo
        let {userinfo} = this.props;
        //console.log(userinfo)
        if(userinfo.username){
            //已登录（跳转到用户中心页面）
            this.goUserPage()
        }else{
            //未登录
            this.setState({
                checking: false
            });
        }
    }
    //跳转到用户中心页面
    goUserPage(){
        hashHistory.push('/User')
    }
    //用户输入登录信息后存储到redux中
    loginHandle(username){
        //从redux中取出action,取出userinfo
        let actions = this.props.userInfoActions;
        let userinfo = this.props.userinfo;
        //将username存储到userinfo中
        userinfo.username = username;
        //发布action存储
        actions.updata(userinfo);

        //跳转到指定的页面
        let params = this.props.params;
        let router = params.router;
        if(router){
            //跳转到指定页面
            hashHistory.push(router)
        }else{
            //跳转到用户中心
            this.goUserPage()
        }
    }
}

//-------------------redux react 绑定--------------------
function mapStateToProps(state) {
    return {
        userinfo: state.userinfo
    }
}
function mapDispatchToProps(dispatch) {
    return {
        userInfoActions: bindActionCreators(userInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login)    